<template>
  <div class="example-container">
    <h2>VirtualEditableTable 基础示例</h2>

    <div class="controls">
      <button @click="addRow">添加行</button>
      <button @click="saveAll">保存所有</button>
      <button @click="cancelAll">取消所有</button>
      <button @click="toggleLoading">切换加载状态</button>
    </div>

    <div class="table-wrapper">
      <VirtualEditableTable
        ref="tableRef"
        :data="tableData"
        :columns="columns"
        :row-config="rowConfig"
        :edit-config="editConfig"
        :save-adapter="saveAdapter"
        :loading="loading"
        :row-class-name="getRowClassName"
        @edit-activated="onEditActivated"
        @edit-closed="onEditClosed"
        @save-success="onSaveSuccess"
        @save-error="onSaveError"
        @current-change="onCurrentChange"
      />
    </div>

    <div class="info-panel">
      <h3>操作日志</h3>
      <div class="log-container">
        <div v-for="(log, index) in logs" :key="index" class="log-item">
          <span class="log-time">{{ log.time }}</span>
          <span class="log-type" :class="log.type">{{ log.type }}</span>
          <span class="log-message">{{ log.message }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { VirtualEditableTable } from '../index'
import type { SaveAdapter, EditConfig, RowConfig } from '../index'

// 表格引用
const tableRef = ref()

// 表格配置
const rowConfig: RowConfig = {
  keyField: 'id',
  minHeight: 50
}

const editConfig: EditConfig = {
  trigger: 'contenteditable',
  mode: 'row',
  showInsertStatus: true,
  debounceTime: 100
}

// 列配置
const columns = [
  { field: 'id', title: 'ID', width: 80, editable: false },
  { field: 'name', title: '姓名', width: 150, editable: true },
  { field: 'email', title: '邮箱', width: 200, editable: true },
  { field: 'phone', title: '电话', width: 150, editable: true },
  { field: 'address', title: '地址', editable: true },
  { field: 'status', title: '状态', width: 100, editable: true }
]

// 表格数据
const tableData = ref([
  {
    id: '1',
    name: '张三',
    email: 'zhangsan@example.com',
    phone: '13800138001',
    address: '北京市朝阳区xxx街道',
    status: '正常'
  },
  {
    id: '2',
    name: '李四',
    email: 'lisi@example.com',
    phone: '13800138002',
    address: '上海市浦东新区xxx路',
    status: '正常'
  },
  {
    id: '3',
    name: '王五',
    email: 'wangwu@example.com',
    phone: '13800138003',
    address: '广州市天河区xxx大道',
    status: '禁用'
  }
])

// 生成更多测试数据
for (let i = 4; i <= 1000; i++) {
  tableData.value.push({
    id: String(i),
    name: `用户${i}`,
    email: `user${i}@example.com`,
    phone: `1380013${String(i).padStart(4, '0')}`,
    address: `城市${i}区xxx路${i}号`,
    status: i % 5 === 0 ? '禁用' : '正常'
  })
}

// 保存适配器
const saveAdapter: SaveAdapter = {
  async editRow(row: any) {
    // 模拟API调用
    await new Promise((resolve) => setTimeout(resolve, 500 + Math.random() * 1000))

    // 模拟随机失败
    if (Math.random() < 0.1) {
      throw new Error('网络错误，保存失败')
    }

    addLog('success', `保存成功: ${row.name} (ID: ${row.id})`)

    // 返回更新后的数据
    return {
      ...row,
      updatedAt: new Date().toISOString()
    }
  }
}

// 状态
const loading = ref(false)
const logs = ref<Array<{ time: string; type: string; message: string }>>([])

// 添加日志
const addLog = (type: string, message: string) => {
  logs.value.unshift({
    time: new Date().toLocaleTimeString(),
    type,
    message
  })

  // 保持最近50条日志
  if (logs.value.length > 50) {
    logs.value = logs.value.slice(0, 50)
  }
}

// 事件处理
const onEditActivated = ({ row, field }: { row: any; field?: string }) => {
  addLog('info', `开始编辑: ${row.name} -> ${field}`)
}

const onEditClosed = ({
  row,
  field,
  changed,
  error
}: {
  row: any
  field?: string
  changed: boolean
  error?: any
}) => {
  if (error) {
    addLog('error', `编辑失败: ${row.name} -> ${field} (${error.message})`)
  } else if (changed) {
    addLog('info', `编辑完成: ${row.name} -> ${field}`)
  } else {
    addLog('info', `无变化: ${row.name} -> ${field}`)
  }
}

const onSaveSuccess = ({ row, result }: { row: any; result: any }) => {
  // 更新本地数据
  const index = tableData.value.findIndex((item) => item.id === row.id)
  if (index >= 0) {
    tableData.value[index] = { ...tableData.value[index], ...result }
  }
}

const onSaveError = ({ row, error }: { row: any; error: any }) => {
  addLog('error', `保存失败: ${row.name} (${error.message})`)
}

const onCurrentChange = ({ row }: { row: any }) => {
  addLog('info', `当前行变化: ${row.name}`)
}

// 操作方法
const addRow = () => {
  const newId = String(Date.now())
  const newRow = {
    id: newId,
    name: `新用户${newId.slice(-4)}`,
    email: `newuser${newId.slice(-4)}@example.com`,
    phone: '13800138000',
    address: '新地址',
    status: '正常'
  }

  tableData.value.unshift(newRow)
  addLog('info', `添加新行: ${newRow.name}`)
}

const saveAll = () => {
  tableRef.value?.saveAll()
  addLog('info', '保存所有编辑')
}

const cancelAll = () => {
  tableRef.value?.cancelAll()
  addLog('info', '取消所有编辑')
}

const toggleLoading = () => {
  loading.value = !loading.value
  addLog('info', `加载状态: ${loading.value ? '开启' : '关闭'}`)
}

// 行样式
const getRowClassName = (row: any, index: number): string => {
  if (row.status === '禁用') {
    return 'row-disabled'
  }
  return ''
}

// 初始日志
addLog('info', '示例已加载，开始编辑吧！')
</script>

<style scoped>
.example-container {
  padding: 20px;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.controls {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.controls button {
  padding: 8px 16px;
  border: 1px solid #d0d7de;
  border-radius: 6px;
  background-color: #f6f8fa;
  cursor: pointer;
  transition: all 0.2s;
}

.controls button:hover {
  background-color: #f3f4f6;
  border-color: #8c959f;
}

.table-wrapper {
  flex: 1;
  min-height: 400px;
  margin-bottom: 20px;
}

.info-panel {
  height: 200px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  padding: 16px;
}

.info-panel h3 {
  margin: 0 0 12px 0;
  font-size: 16px;
  color: #333;
}

.log-container {
  height: calc(100% - 40px);
  overflow-y: auto;
  font-family: 'Courier New', monospace;
  font-size: 12px;
}

.log-item {
  display: flex;
  margin-bottom: 4px;
  padding: 2px 0;
}

.log-time {
  width: 80px;
  color: #666;
  margin-right: 8px;
}

.log-type {
  width: 60px;
  margin-right: 8px;
  font-weight: bold;
}

.log-type.info {
  color: #0969da;
}

.log-type.success {
  color: #1a7f37;
}

.log-type.error {
  color: #d1242f;
}

.log-message {
  flex: 1;
  color: #333;
}

/* 表格行样式 */
:deep(.row-disabled) {
  background-color: #ffeaea !important;
  color: #999;
}

:deep(.row-disabled:hover) {
  background-color: #ffdddd !important;
}
</style>
